package com.blast.manager.net.ui

import android.view.KeyEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.fastjson.JSONArray
import com.blast.manager.R
import com.blast.manager.adapter.DetonatorAdapter
import com.wxl.common.AppContext
import com.wxl.common.base.AbsActivity
import com.wxl.common.room.entity.LeiGuanBlastEntity
import com.wxl.common.room.entity.LeiGuanDelayEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.LayoutHelper
import com.wxl.common.util.ObservableUtil
import kotlinx.android.synthetic.main.activity_detonator_list_layout.*

class DetonatorListActivity : AbsActivity() {

    lateinit var mDetonatorAdapter: DetonatorAdapter

    override fun getCreateContentViewId(): Int {
        return R.layout.activity_detonator_list_layout
    }

    override fun onCreateViewChanged() {
        setTopTitle("雷管列表")
        isCheckAppUpgrade = false
        detonatorListView.layoutManager = LinearLayoutManager(this)
        if (intent.hasExtra("key")) {
            val key = intent.getStringExtra("key")
            mDetonatorAdapter = DetonatorAdapter(AppContext.appContext.getLeiGuanDelayEntity(key!!))
            showData()
        } else {
            val blastId = intent.getStringExtra("blastId")
            DBHelper.queryBlastedLeiGuan(object: ObservableUtil.Companion.OnNextCallback<List<LeiGuanBlastEntity>>(){
                override fun onNext(t: List<LeiGuanBlastEntity>) {
                    dismissClearAllPop()
                    val data = JSONArray.parseArray(JSONArray.toJSONString(t),LeiGuanDelayEntity::class.java)
                    mDetonatorAdapter = DetonatorAdapter(data)
                    showData()
                }
            }, blastId!!)

        }


        detonatorCancel.setOnClickListener {
            finish()
        }
    }


    private fun showData(){
        if(mDetonatorAdapter.data.isEmpty()){
            detonatorEmptyView.visibility = View.VISIBLE
            detonatorListView.visibility = View.GONE
        } else {
            detonatorEmptyView.visibility = View.GONE
            detonatorListView.visibility = View.VISIBLE
        }
        LayoutHelper.getDetonatorTitleViewsWidth(detonatorTitleLayout,object : ObservableUtil.Companion.OnNextCallback<ArrayList<Int>>(){
            override fun onNext(t: ArrayList<Int>) {
                mDetonatorAdapter.setWidths(t)
                mDetonatorAdapter.bindToRecyclerView(detonatorListView)
            }
        })
    }

    override fun onKeyDownEvent(keyCode: Int, event: KeyEvent?): Boolean {
        mDetonatorAdapter.onKeyDown(keyCode, event)
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_F1) {
            detonatorCancel.performClick()
        }
        return true
    }
}